package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.entity.Coupon;
import com.foodorder.entity.UserCoupon;
import com.foodorder.service.CouponService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 优惠券控制器
 */
@RestController
@RequestMapping("/coupons")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class CouponController {
    
    private final CouponService couponService;
    
    /**
     * 获取店铺优惠券列表
     */
    @GetMapping("/store/{storeId}")
    public ApiResponse<List<Coupon>> getStoreGrabbableCoupons(@PathVariable Long storeId) {
        List<Coupon> coupons = couponService.findGrabbableCoupons(storeId);
        return ApiResponse.success(coupons);
    }
    
    /**
     * 管理端分页查询优惠券
     */
    @GetMapping("/admin")
    public ApiResponse<Map<String, Object>> getCouponsForAdmin(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Long storeId) {
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<Coupon> couponPage = couponService.findCouponsForAdmin(keyword, status, type, storeId, pageable);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", couponPage.getContent());
            result.put("total", couponPage.getTotalElements());
            result.put("page", page);
            result.put("size", size);
            result.put("totalPages", couponPage.getTotalPages());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("查询优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取平台优惠券
     */
    @GetMapping("/platform")
    public ApiResponse<List<Coupon>> getPlatformCoupons() {
        List<Coupon> coupons = couponService.findPlatformCoupons();
        return ApiResponse.success(coupons);
    }
    
    /**
     * 获取用户优惠券列表
     */
    @GetMapping("/user/{userId}")
    public ApiResponse<List<UserCoupon>> getUserCoupons(@PathVariable Long userId) {
        List<UserCoupon> userCoupons = couponService.findUserAvailableCoupons(userId);
        return ApiResponse.success(userCoupons);
    }
    
    /**
     * 获取用户在指定店铺可用的优惠券
     */
    @GetMapping("/user/{userId}/store/{storeId}")
    public ApiResponse<List<UserCoupon>> getUserCouponsForStore(
            @PathVariable Long userId,
            @PathVariable Long storeId) {
        List<UserCoupon> userCoupons = couponService.findUserAvailableCouponsForStore(userId, storeId);
        return ApiResponse.success(userCoupons);
    }
    
    /**
     * 抢红包/领取优惠券
     */
    @PostMapping("/{couponId}/claim")
    public ApiResponse<String> claimCoupon(
            @PathVariable Long couponId,
            @RequestParam Long userId) {
        boolean success = couponService.claimCoupon(userId, couponId);
        if (success) {
            return ApiResponse.success("领取成功");
        } else {
            return ApiResponse.error("领取失败，请检查优惠券状态或领取条件");
        }
    }
    
    /**
     * 获取可用优惠券（下单时）
     */
    @GetMapping("/available")
    public ApiResponse<List<Coupon>> getAvailableCoupons(
            @RequestParam Long storeId,
            @RequestParam BigDecimal orderAmount) {
        List<Coupon> coupons = couponService.findAvailableCoupons(storeId, orderAmount);
        return ApiResponse.success(coupons);
    }
    
    /**
     * 创建优惠券（商家功能）
     */
    @PostMapping
    public ApiResponse<Coupon> createCoupon(@RequestBody Coupon coupon) {
        try {
            Coupon savedCoupon = couponService.createCoupon(coupon);
            return ApiResponse.success(savedCoupon);
        } catch (Exception e) {
            return ApiResponse.error("创建优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新优惠券
     */
    @PutMapping("/{id}")
    public ApiResponse<Coupon> updateCoupon(@PathVariable Long id, @RequestBody Coupon coupon) {
        try {
            Coupon existingCoupon = couponService.findById(id);
            if (existingCoupon == null) {
                return ApiResponse.error("优惠券不存在");
            }
            coupon.setId(id);
            Coupon savedCoupon = couponService.updateCoupon(coupon);
            return ApiResponse.success(savedCoupon);
        } catch (Exception e) {
            return ApiResponse.error("更新优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除优惠券
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteCoupon(@PathVariable Long id) {
        try {
            Coupon coupon = couponService.findById(id);
            if (coupon == null) {
                return ApiResponse.error("优惠券不存在");
            }
            couponService.deleteCoupon(id);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("删除优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除优惠券
     */
    @DeleteMapping("/batch")
    public ApiResponse<Void> deleteCoupons(@RequestBody List<Long> ids) {
        try {
            couponService.deleteByIds(ids);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("批量删除优惠券失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新优惠券状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateCouponStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            couponService.updateStatus(id, status);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新优惠券状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取优惠券详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Coupon> getCouponDetail(@PathVariable Long id) {
        Coupon coupon = couponService.findById(id);
        if (coupon == null) {
            return ApiResponse.notFound("优惠券不存在");
        }
        return ApiResponse.success(coupon);
    }
    
    /**
     * 获取优惠券统计信息
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Object>> getCouponStatistics() {
        try {
            Map<String, Object> statistics = couponService.getCouponStatistics();
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            return ApiResponse.error("获取优惠券统计失败: " + e.getMessage());
        }
    }
} 